//
//  AddFunyPicViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/5/9.
//

#import "AddFunyPicViewController.h"
#import "AddFunyPicCollectionViewCell.h"
#import "AddModel.h"
@interface AddFunyPicViewController ()<UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (nonatomic , strong) FSTextView * fsTextView;
@property (nonatomic , strong) HeaderView * addButton;
@end

@implementation AddFunyPicViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}

- (void)SQ_UIViewForSelfView{
    
    UILabel * label = [[UILabel alloc]init];
    label.text = SQNSLocalString(@"分享快乐");
    label.font = FONT_MEDIUM(20);
    label.textColor = UIColor.whiteColor;
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view).offset(TopHeight-30);
    }];
    
    SQCustomButton * add = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(30, 30) midmargin:0];
    add.image = SQGetImage(@"不喜欢");
    [self.view addSubview:add];
    [add mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(label);
        make.size.mas_equalTo(50);
        make.right.equalTo(self.view.mas_right).offset(-4);
    }];
    WS(weakSelf);
    [add setTouchBlock:^(SQCustomButton * _Nonnull button) {
        if ([weakSelf.fsTextView.formatText isNotEmpty]||weakSelf.jsonArray.count >1) {
            [weakSelf SQ_tuichuButtonClick];
        } else {
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        }
    }];
    
    UIView * bgView = [[UIView alloc]init];
    bgView .backgroundColor = SQHexColor(@"#303030", 1);
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    bgView.layer.cornerRadius = 20;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(SCREEN_WIDETH-30);
        make.top.equalTo(label.mas_bottom).offset(40);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(200);
    }];
    [bgView addSubview:self.fsTextView];
    [self.fsTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(bgView).insets(UIEdgeInsetsMake(10, 10, 10, 10));
    }];
    
    
    [self.collectionView registerClass:[AddFunyPicCollectionViewCell class] forCellWithReuseIdentifier:@"AddFunyPicCollectionViewCell"];
    [self.view addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(bgView.mas_bottom).offset(20);
        make.bottom.equalTo(self.view.mas_bottom).offset(-120);
    }];
    
    [self.view addSubview:self.addButton];
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(SCREEN_WIDETH-60);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-30);
        make.height.mas_equalTo(48);
    }];
    
    
    AddModel * model = [AddModel new];
    model.isAdd = YES;
    [self.jsonArray addObject:model];
    [self.collectionView reloadData];
    
}
-(void)SQ_ButtonClick{
    if (![_fsTextView.formatText isNotEmpty]) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"简单的讲两句吧!")];
        return;
    }
    if (self.jsonArray.count <=1) {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"分享点有趣的图片吧!")];
        return;
    }
    NSMutableArray * array = [[NSMutableArray alloc]init];
    for (AddModel * model in self.jsonArray) {
        if (model.isAdd) {
            continue;
        }
        [YJProgressHUD SQ_showMsgWithoutView:@""];
        [HttpTool SQ_Image:model.addImage successBlock:^(BaseModel * _Nonnull httpModel) {
            NSString * imageurl = [NSString stringWithFormat:@"%@",httpModel.data];
            if (self.jsonArray.count==2) {
                //只有一张
                imageurl = [NSString stringWithFormat:@"%@&%.f&%.f",imageurl,model.addImage.size.width,model.addImage.size.height];
                [array addObject:imageurl];
            }else{
                [array addObject:httpModel.data];
            }
            if (array.count+1 == self.jsonArray.count) {
                [self SQ_uplode:array];
            }
        } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
            
        }];
        
    }
}
-(void)SQ_uplode:(NSMutableArray*)array{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[array componentsJoinedByString:@","] forKey:@"imgs"];
    [dic setObject:self.fsTextView.formatText forKey:@"content"];
    [HttpTool post:Url36 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}

#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.jsonArray.count >9) {
        return 9;
    }
    return self.jsonArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    AddFunyPicCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddFunyPicCollectionViewCell" forIndexPath:indexPath];
    AddModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    model.index = self.jsonArray.count - 1;
    cell.model = model;
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
   
    return CGSizeMake((SCREEN_WIDETH-30)/3.f-1, (SCREEN_WIDETH-30)/3.f-1);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 0, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    AddModel * model = [self.jsonArray objectAtIndex:indexPath.item];
    if (model.isAdd) {
        [self SQ_headerButtonClick];
    }else{
        [self SQ_deletedButtonClick:indexPath];
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
-(void)SQ_deletedButtonClick:(NSIndexPath*)indexPath{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"是否删除该照片") message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co1 = [UIAlertAction actionWithTitle:SQNSLocalString(@"删除") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.jsonArray removeObjectAtIndex:indexPath.item];
        [weakSelf.collectionView reloadData];
    }];
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co1];
    [alert addAction:co2];
    [[Manager SQ_getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}
 
-(void)SQ_headerButtonClick{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"选择照片") message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"拍照") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf SQ_leftButtonClick];
    }];
    UIAlertAction * co1 = [UIAlertAction actionWithTitle:SQNSLocalString(@"相册") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf SQ_rightButtonClick];
    }];
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co1];
    [alert addAction:co2];
    [[Manager SQ_getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}

-(void)SQ_leftButtonClick{
    WS(weakSelf);
    _imagePickerVc = [[UIImagePickerController alloc] init];
    _imagePickerVc.delegate = self;
    _imagePickerVc.allowsEditing = YES;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
        weakSelf.imagePickerVc.sourceType = sourceType;
        [[Manager SQ_getCurrentViewController] presentViewController:weakSelf.imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    WS(weakSelf);
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *photo = [info objectForKey:UIImagePickerControllerEditedImage];
        if (photo == nil)
            {
                photo = [info objectForKey:UIImagePickerControllerOriginalImage];
            }
        [weakSelf SQ_caijian:photo];
    }else
    {
        [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"相册数据异常")];
    }
}


-(void)SQ_rightButtonClick{
    WS(weakSelf);
    TZImagePickerController * vc = [[TZImagePickerController alloc]init];
    vc.maxImagesCount = 10-self.jsonArray.count;
    vc.allowPickingVideo = NO;
    vc.scaleAspectFillCrop = NO;
    [[Manager SQ_getCurrentViewController] presentViewController:vc animated:YES completion:nil];
    [vc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        for (UIImage * image in photos) {
            [weakSelf SQ_caijian:image];
        }
    }];
}

//添加图片到列表
-(void)SQ_caijian:(UIImage*)image {
    AddModel * model = [AddModel new];
    model.addImage = image;
    [self.jsonArray insertObject:model atIndex:0];
    [self.collectionView reloadData];
    
}

-(void)SQ_tuichuButtonClick{
    WS(weakSelf);
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:SQNSLocalString(@"是否退出") message:SQNSLocalString(@"确认退出将无法保存已填写内容") preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * co0 = [UIAlertAction actionWithTitle:SQNSLocalString(@"确认退出") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    UIAlertAction * co2 = [UIAlertAction actionWithTitle:SQNSLocalString(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:co0];
    [alert addAction:co2];
    [[Manager SQ_getCurrentViewController] presentViewController:alert animated:YES completion:nil];
}


-(FSTextView*)fsTextView{
    if (!_fsTextView) {
        _fsTextView = [FSTextView textView];
        _fsTextView.font = FONT_MEDIUM(15);
        _fsTextView.textColor = UIColor.whiteColor;
        _fsTextView.placeholder =SQNSLocalString(@"分享一些有趣的事~");
        _fsTextView.placeholderColor = SQColor999999;
        _fsTextView.backgroundColor = UIColor.clearColor;
        _fsTextView.maxLength = 200;
       
    }
    return _fsTextView;
}

- (HeaderView *)addButton{
    if (!_addButton) {
        _addButton = [[HeaderView alloc]init];
        _addButton.image = @"矩形";
        _addButton.colorString = @"#FFFFFF";
        [_addButton.btn addTarget:self action:@selector(SQ_ButtonClick) forControlEvents:UIControlEventTouchUpInside];
        _addButton.layer.masksToBounds = YES;
        _addButton.headerImage.contentMode = UIViewContentModeScaleAspectFill;
        _addButton.headerImage.clipsToBounds = YES;
        _addButton.layer.cornerRadius = 24;
        _addButton.layer.masksToBounds = YES;
        _addButton.text = SQNSLocalString(@"提交");
        _addButton.font = FONT_MEDIUM(18);
    }
    return _addButton;
}
@end
